const db = require('../../mysql')
const fs = require('fs')
const path = require('path')
const common = require("../../utils/common")

// 获取侧边导航列表
exports.asideList = (req, res) => {
    const asideSql = 'SELECT * FROM backstage_aside'
    db.query(asideSql, (err, result) => {
        if (err) return res.cc(err)
        if(result.length !== 0) {
            const asideData = common.toTree(result)
            res.send({
            status: 0,
            data: asideData,
            message: '获取列表成功',
        })
        }
    })
}

// 获取每日浏览量
exports.getDayBrowse = (req, res) => {
    const date = new Date()
    const now = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    const getDaySql = 'SELECT * FROM class_category where Date(day_time)=?'
    db.query(getDaySql, now, (err, result) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            data: result,
            message: '获取每日浏览量成功',
        })
    })
}

// 获取全部浏览量
exports.getAllBrowse = (req, res) => {
    const date = new Date()
    const now = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    const getAllSql = 'SELECT total_access, mouth_access, day_access, total_subscribe, mouth_subscribe, day_subscribe FROM data_analyse WHERE Date(time)=?'
    db.query(getAllSql, [now], (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 0) {
            let data = [
                { name: '总浏览量', count: result[0].total_access, icon: 'el-icon-box', color: '#132462' },
                { name: '月浏览量', count: result[0].mouth_access, icon: 'el-icon-moon', color: '#123129' },
                { name: '日浏览量', count: result[0].day_access, icon: 'el-icon-sunny', color: '#132edf' },
                { name: '总订阅量', count: result[0].total_subscribe, icon: 'el-icon-box', color: '#354651' },
                { name: '月订阅量', count: result[0].mouth_subscribe, icon: 'el-icon-moon', color: '#265420' },
                { name: '日订阅量', count: result[0].day_subscribe, icon: 'el-icon-sunny', color: '#451230' }
            ]
            res.send({
                status: 200,
                data: data
            })
        } else {
            res.cc("数据获取失败")
        }
    })
}


// 新增教材
exports.addTextBook = (req, res) => {
    // console.log(req.file);
    const reqInfo = req.body
    console.log(reqInfo);
    console.log(reqInfo.name);
    fs.readFile(req.file.path, (err, data) => {
        //读取失败，说明没有上传成功
        if (err) { return res.send('上传失败') }
        //声明图片名字为时间戳和随机数拼接成的，尽量确保唯一性
        let time = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random() * 2222);
        //拓展名
        let extname = req.file.mimetype.split('/')[1]
        //拼接成图片名
        let keepname = time + '.' + extname
        //绝对路径就可以写成以下形式
        const filePath = path.join(__dirname, '../public/textbook_images/' + keepname)

        //否则读取成功，开始写入
        //我们先尝试用原文件名originalname写入吧
        // 三个参数
        //1.图片的绝对路径
        //2.写入的内容
        //3.回调函数  
        fs.writeFile(filePath, data, (err) => {
            if (err) { return res.send('写入失败') }
            // res.send({ err: 0, msg: '上传ok' })
            const addTextBookSql = 'INSERT INTO textbook(name,picture,publish,state) VALUE(?,?,?,0)'
            const addPath = 'http://localhost:10001/static/textbook_images/' + keepname
            db.query(addTextBookSql, [reqInfo.name, addPath, reqInfo.publish], (err, result) => {
                if (err) return res.cc(err)
                console.log(result);
                res.send({
                    status: 0,
                    msg: '上传ok',
                    data: '/img/' + keepname
                })
            })
        })
    })
}

// 获取教材
exports.getTextBook = (req, res) => {
    const getCountSql = 'SELECT COUNT(*) FROM class_category'
    const getInfo = req.query
    const start = (getInfo.currentPage - 1) * getInfo.pageSize
    const end = getInfo.pageSize * 1
    const a = new Promise((resolve, reject) => {
        db.query(getCountSql, (err, result) => {
            if (err) {
                reject(err)
            } else {
                resolve(result[0]['COUNT(*)'])
            }
        })
    })

    a.then(value => {
        const getTextBookSql = 'SELECT * FROM class_category where state=1 limit ?,?'
        db.query(getTextBookSql, [start, end], (err, result) => {
            if (err) return res.cc(err)
            if (result.length !== 0) {
                res.send({
                    status: 0,
                    data: {
                        total: value,
                        result,
                    },
                    message: "获取教材列表成功"
                })
            }
        })
    }, reason => {
        console.log(reason);
    })


}
// 更新教材
exports.updateTextBook = (req, res) => {
    const updateinfo = req.body
    const updateSql = 'UPDATE textbook SET name=?,publish=? where id=?'
    db.query(updateSql, [updateinfo.name, updateinfo.publish, updateinfo.id], (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows === 1) {
            res.send({
                status: 0,
                message: '更新数据成功'
            })
        } else { res.cc("更新数据失败") }
    })
}
// 删除教材
exports.deleteTextBook = (req, res) => {
    const textInfo = req.body
    console.log(textInfo);
    const deleteTextBookSql = 'UPDATE textbook SET state=1 WHERE id=?'
    db.query(deleteTextBookSql, textInfo.id, (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows === 1) {
            res.send({
                status: 0,
                message: '删除教材成功'
            })
        }
    })
}
// 搜索教材
exports.searchTextBook = (req, res) => {
    const searchinfo = req.query
    // console.log(searchinfo);
    const searchTextBookSql = `SELECT * FROM textbook where name LIKE '%${searchinfo.keyword}%' AND state=0`
    db.query(searchTextBookSql, (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 0) {
            res.send({
                status: 0,
                data: {
                    total: result.length,
                    result
                },
                message: '搜索到教材'
            })
        } else { res.cc('没有搜索到教材') }
    })
}

// 更新时间
function insertData() {
    const date = new Date()
    const now = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    const catSql = 'SELECT day_time from class_category where Date(day_time)=?'
    const updateSql = 'UPDATE class_category SET day_time=?'
    const updateSql2 = 'INSERT INTO data_analyse (time,total_access,mouth_access,day_access,total_subscribe, mouth_subscribe, day_subscribe) VALUES (?,"7650","689","38","5468","354","25")'
    new Promise((resolve, reject) => {
        db.query(catSql, now, (err, result) => {
            if (err) {
                reject(err)
            }
            if (result.length === 0) {
                resolve()
            }
        })
    }).then(value => {
        db.query(updateSql, now, (err, result) => {
            if (err) {
                console.log(err);
            } else if (result.affectedRows !== 0) {
                console.log("修改日期成功");
            }
        })
    }).catch(err => {
        console.log(err);
    })
    // 
    db.query(updateSql2, now, (err, result) => {
        if (err) res.cc(err)
        if (result.affectedRows !== 0) {
            console.log("修改成功");
        }
    })
}

function updataTime() {
    const now = new Date()
    const time = now.getUTCDate()
    db.query('SELECT day_time from class_category limit 1', (err, result) => {
        console.log(result);
        console.log(time);
        console.log(result[0].day_time.getUTCDate());
        if(time != result[0].day_time.getUTCDate()+1){
            insertData()
            setTimeout(() => {
                console.log("更新时间");
                updataTime()
            }, 5*60*60*1000);
        } else {
            return
        }
        
    })
}
// updataTime()